<template>
  <el-drawer v-model="drawer" :before-close="handleClose" size="70%" modal-class="pay-drawer">
    <template #header>
      <div style="display: flex; align-items: center">
        <title-view title="确认发包明细" />
      </div>
    </template>
    <div style="display: flex; justify-content: space-between; align-items: center">
      <div style="display: flex; align-items: center">
        <el-button type="primary" style="width: 116px" :icon="Plus" @click="handleAdd">添加发包项</el-button>
        <div v-if="approvalType === 4" style="margin-left: 10px; color: #ff9900">
          当前发包清单存在编辑，待内部审核后生效，已为您展示编辑后的信息。
        </div>
      </div>
      <el-select v-model="type" placeholder="请选择" style="width: 200px" @change="handleChange" clearable @clear="handleChange">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </div>
    <el-table
      ref="myTable"
      class="custom-table"
      :data="tableData"
      row-key="spaceIdTree"
      :height="tableHeight"
      :tree-props="treeProps"
      :expand-row-keys="expandRowKeys"
      :row-class-name="tableRowClassName"
      @expand-change="handleExpandChange"
      style="width: 100%; margin-top: 20px"
      :header-cell-style="{ background: '#F2F6FC', color: '#4E5969', 'font-weight': 400, 'font-size': '14px' }"
    >
      <el-table-column prop="date" label="名称" width="150" show-overflow-tooltip>
        <template #header>
          <div style="display: flex; align-items: center">
            <div>名称</div>
            <div style="margin-top: 8px; margin-left: 6px">
              <img
                v-if="isExpansion"
                @click="toggleExpandAll"
                style="width: 20px; cursor: pointer"
                src="@/assets/images/image/sq.png"
                alt=""
              />
              <img
                v-else
                @click="toggleExpandAll"
                style="width: 20px; cursor: pointer"
                src="@/assets/images/image/zk.png"
                alt=""
              />
            </div>
          </div>
        </template>
        <template #default="{ row }">
          {{ row.quotaInfoVOList ? row.spaceName : row.quotaName }}
        </template>
      </el-table-column>
      <el-table-column prop="" label="明细" show-overflow-tooltip>
        <template #default="{ row }">
          <span v-if="row.mainSubcontractMoney">主材：￥{{ row.mainSubcontractMoney }}/</span>
          <span v-if="row.auxiliarySubcontractMoney">辅材：¥{{ row.auxiliarySubcontractMoney }}/</span>
          <span v-if="row.workerSubcontractMoney">人工：¥{{ row.workerSubcontractMoney }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="unit" label="单位" show-overflow-tooltip width="60">
        <template #default="{ row }">
          {{ unitData.find(item => item.dictValue == row.unit)?.dictLabel }}
        </template>
      </el-table-column>
      <el-table-column prop="actualProjectVal" label="实际施工量" show-overflow-tooltip />
      <el-table-column prop="contracteesNum" label="发包量" width="100">
        <template #default="{ row }">
          <el-input-number
            v-if="!row.quotaInfoVOList"
            style="width: 100%"
            :min="0"
            v-model="row.contracteesNum"
            :controls="false"
            placeholder="请输入"
            :precision="0"
          />
        </template>
      </el-table-column>
      <el-table-column prop="subcontractTotalMoney" label="发包单价" width="100">
        <template #default="{ row }">
          <el-input-number
            v-if="!row.quotaInfoVOList"
            style="width: 100%"
            :min="0"
            v-model="row.subcontractTotalMoney"
            :controls="false"
            placeholder="请输入"
            :precision="2"
          />
        </template>
      </el-table-column>
      <el-table-column prop="subcontractTotalMoneyCnt" label="发包价(发包量*单价)" show-overflow-tooltip width="160">
        <template #default="{ row }">
          <span v-if="!row.quotaInfoVOList">
            {{ ((row.contracteesNum || 0) * (row.subcontractTotalMoney || 0)).toFixed(2) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="bindNames" label="品牌" show-overflow-tooltip />
      <el-table-column prop="modelNames" label="型号" show-overflow-tooltip />
      <el-table-column label="操作" width="60" fixed="right">
        <template #default="{ row }">
          <span style="color: #409eff; cursor: pointer" @click="handleRemove(row)">移除</span>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <div style="display: flex; justify-content: space-between; align-items: center">
        <div>
          <span>共{{ listNum || 0 }}项，总计发包金额：</span>
          <span style="color: #ea0000">¥{{ listMoneyTotal || 0 }}</span>
          <span style="color: #ea0000" v-if="contracteesType === 2"
            >（该项目为按面积发包模式，实际发包金额¥{{ factMoney || 0 }}）</span
          >
        </div>
        <div>
          <el-button @click="handleClose" color="#F2F3F5">取消</el-button>
          <el-button type="primary" plain @click="saveClick" v-if="state === 2">保存</el-button>
          <el-button type="primary" @click="confirmClick">确认发起申请</el-button>
        </div>
      </div>
    </template>
  </el-drawer>
  <Add ref="add" @handleActive="handleActive" />
</template>
<script setup>
import Add from "./add.vue";
import { computed, nextTick, ref } from "vue";
import { Plus } from "@element-plus/icons-vue";
import { queryInfoList, removeContractees, save, submit } from "@/apis/contracting";
import { getCache } from "@/utils/cache";
import { selectDictDataByType } from "@/apis/dict/dict";
import { ElMessage } from "element-plus";

const treeProps = ref({
  checkStrictly: false,
  children: "quotaInfoVOList"
});
const tableData = ref([]);
const options = ref([
  {
    value: 1,
    label: "主材"
  },
  {
    value: 2,
    label: "辅材"
  },
  {
    value: 3,
    label: "人工"
  }
]);
const tableHeight = ref(600);
const approvalType = ref();
const contracteesId = ref();
const contracteesType = ref();
const factMoney = ref();
const state = ref();
const expandRowKeys = ref([]);
const myTable = ref();
const add = ref();
const type = ref();
const unitData = ref([]);
const emit = defineEmits(["handelSearch"]);
const drawer = ref(false);
const isExpansion = ref(false);

const listMoneyTotal = computed(() => {
  let numMoney = 0;
  tableData.value.map(item => {
    item.quotaInfoVOList.map(items => {
      numMoney += (items.contracteesNum || 0) * (items.subcontractTotalMoney || 0);
    });
  });
  return numMoney.toFixed(2);
});
const listNum = computed(() => {
  let num = 0;
  tableData.value.map(item => {
    item.quotaInfoVOList.map(() => (num += 1));
  });
  return num;
});

// 获取选中后端发包项
const handleActive = () => {
  getQueryInfoList();
};
// 关闭
const handleClose = () => {
  drawer.value = false;
};
const saveClick = async () => {
  if (contracteesType.value === 1 && tableData.value.length <= 0) {
    ElMessage.error("按清单发包必须添加发包项！");
    return;
  }
  await save({
    contracteesId: contracteesId.value,
    details: tableData.value
  });
  ElMessage.success("保存成功！");
  emit("handelSearch");
  drawer.value = false;
};
// 提交
const confirmClick = async () => {
  if (contracteesType.value === 1 && tableData.value.length <= 0) {
    ElMessage.error("按清单发包必须添加发包项！");
    return;
  }
  const { msg } = await submit({
    contracteesId: contracteesId.value,
    details: tableData.value
  });
  ElMessage.success(msg);
  emit("handelSearch");
  drawer.value = false;
};

const openDrawer = row => {
  isExpansion.value = true;
  expandRowKeys.value = [];
  approvalType.value = row.approvalType;
  contracteesId.value = row.contracteesId;
  contracteesType.value = row.contracteesType;
  factMoney.value = row.factMoney;
  state.value = row.state;
  getQueryInfoList();
  drawer.value = true;
  setHeight();
  getUnit();
};
const handleChange = () => {
  getQueryInfoList();
};
const getQueryInfoList = async () => {
  const { data } = await queryInfoList({
    contracteesId: contracteesId.value,
    code: getCache("randomCode"),
    type: type.value
  });
  let ids = [];
  data.map(item => {
    ids.push(item.spaceId);
  });
  expandRowKeys.value = ids;
  data.map(item => {
    item.quotaInfoVOList.map(items => {
      if (!items.contracteesNum) {
        items.contracteesNum = items.actualProjectVal;
      }
    });
  });
  tableData.value = data;
};
// 移除
const handleRemove = async row => {
  console.log(row);
  let contentIds = [];
  if (row.quotaInfoVOList?.length > 0) {
    row.quotaInfoVOList.map(item => {
      contentIds.push(item.spaceIdTree);
    });
  } else {
    contentIds = [row.spaceIdTree];
  }
  await removeContractees({ contentIds, code: getCache("randomCode") });
  getQueryInfoList();
};
const getUnit = async () => {
  const { data } = await selectDictDataByType("shop_unit");
  unitData.value = data || [];
};
// 查询
const handleAdd = () => {
  add.value.openDrawer(contracteesId.value);
};
const toggleExpandAll = () => {
  isExpansion.value = !isExpansion.value;
  if (isExpansion.value) {
    toggleRowExpansionAll(tableData.value, isExpansion);
  } else {
    expandRowKeys.value = [];
  }
};
const toggleRowExpansionAll = (data, isExpansion) => {
  data.forEach(item => {
    myTable.value.toggleRowExpansion(item, isExpansion);
    if (item.quotaInfoVOList !== undefined && item.quotaInfoVOList !== null) {
      toggleRowExpansionAll(item.quotaInfoVOList, isExpansion);
    }
  });
};
const tableRowClassName = ({ row }) => {
  if (expandRowKeys.value.includes(row.spaceIdTree)) {
    return "active-row";
  }
  return "init-row";
};
const handleExpandChange = (row, expanded) => {
  if (expanded) {
    expandRowKeys.value.push(row.spaceIdTree);
  } else {
    const index = expandRowKeys.value.indexOf(row.spaceIdTree);
    if (index !== -1) {
      expandRowKeys.value.splice(index, 1);
    }
  }
  isExpansion.value = expandRowKeys.value.length > 0;
};
const setHeight = () => {
  nextTick(() => {
    tableHeight.value = document.documentElement.clientHeight - 220;
  });
};
defineExpose({ openDrawer });
</script>
<style scoped lang="scss">
.pay-drawer {
  :deep(.el-drawer) {
    min-width: 525px;
    background: #ffffff;
    box-shadow: 4px 5px 16px 0px rgba(4, 19, 74, 0.04) !important;
    border-radius: 20px 0px 0px 20px !important;
  }
}

/* 自定义树状表格图标 */
/* 有子节点 且未展开 */
:deep(.el-table__expand-icon) {
  background: url("@/assets/images/image/zk1.png") no-repeat;
  width: 16px !important;
  height: 16px !important;
  font-size: 16px !important;
  background-size: 16px !important;

  .el-icon {
    display: flex;

    svg {
      width: 0 !important;
    }
  }
}

/* 有子节点 且已展开 */
.custom-table :deep(.el-table__expand-icon--expanded) {
  background: url("@/assets/images/image/sq1.png") no-repeat;
  width: 16px !important;
  height: 16px !important;
  font-size: 16px !important;
  background-size: 16px !important;
  transform: rotate(180deg); /* 展开时旋转 */
  .el-icon {
    display: flex;

    svg {
      width: 0 !important;
    }
  }
}

.custom-table :deep(.active-row) {
  background-color: #d9e8ff !important;
}

.custom-table :deep(.init-row) {
  background-color: #f5f7fa !important;
}

:deep(.el-select__wrapper) {
  background: #f2f3f5 !important;
}
</style>
